import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2cpick/b2cpickfeedbackscreen.dart';
import 'package:opene/ui/b2cpick/b2cpickmodel.dart';
import 'package:opene/ui/b2cpick/b2cpicksubmitscreen.dart';
import 'package:opene/ui/tally/tallymodel.dart';
import 'package:opene/ui/tally/tallyskuscreen.dart';
import 'package:toast/toast.dart';

class B2CPickCategoryScreen extends StatelessWidget {
  B2CPickBean b2cPickBean;
  PickupPol3OBLPN pickupPol3OBLPN;

  B2CPickCategoryScreen({this.b2cPickBean, this.pickupPol3OBLPN});

  @override
  Widget build(BuildContext context) {
    return B2CPickCategoryScreenPage(b2cPickBean: b2cPickBean, pickupPol3OBLPN: pickupPol3OBLPN);
  }
}

class B2CPickCategoryScreenPage extends StatefulWidget {
  B2CPickBean b2cPickBean;
  PickupPol3OBLPN pickupPol3OBLPN;

  B2CPickCategoryScreenPage({this.b2cPickBean, this.pickupPol3OBLPN});

  @override
  _B2CPickCategoryScreenPageState createState() => _B2CPickCategoryScreenPageState(b2cPickBean: b2cPickBean, pickupPol3OBLPN: pickupPol3OBLPN);
}

class _B2CPickCategoryScreenPageState extends BaseState<B2CPickCategoryScreenPage> {
  B2CPickBean b2cPickBean;
  PickupPol3OBLPN pickupPol3OBLPN;

  _B2CPickCategoryScreenPageState({this.b2cPickBean, this.pickupPol3OBLPN});

  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position;
  List<PickupPol3Category> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Pickup:Category";
  }

  @override
  void setFeedBack() {
    // TODO: implement setFeedBack
    super.setFeedBack();
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => B2CPickFeedbackScreen(b2cPickBean: b2cPickBean)),
    ).then((value) => {getTallyContainerNo()});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        feedback = true;
        getTallyContainerNo();
      });
    });
  }

  @override
  Widget getViewBinding() {
    return Container(
      margin: EdgeInsets.only(left: 15, right: 15, top: 10),
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(
              top: 0,
            ),
            child: Row(
              children: [
                Text(
                  "Job    No: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.isBool(b2cPickBean.isNoneLocation) ? "NONE Location" : Utils.getStringisEmpty(b2cPickBean.pickNo),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              top: 0,
            ),
            child: Row(
              children: [
                Text(
                  "OBLPN: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.getStringisEmpty(pickupPol3OBLPN.lpn),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    // setComplete();
                  },
                  child: Container(
                    padding: EdgeInsets.only(left: 5, top: 2, bottom: 2, right: 5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.all(Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Complete',
                      style: MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 10),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  getPickupLpnAndLocation(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        getPickupLpnAndLocation(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan inbound lpn barcode",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Row(
            children: [
              Text(
                "Pick# List:",
                style: MyAppTheme.text,
              ),
              Visibility(
                  visible: Utils.isBool(b2cPickBean.isNoneLocation) ? true : false,
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      // setComplete();
                    },
                    child: Container(
                      padding: EdgeInsets.only(left: 5, top: 2, bottom: 2, right: 5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.all(Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Refresh',
                        style: MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ))
            ],
          ),
          Row(
            children: [
              Expanded(
                  flex: 1,
                  child: Text(
                    "Location",
                    style: MyAppTheme.text,
                  )),
              Expanded(
                  flex: 1,
                  child: Text(
                    "SKU(total/picked)",
                    style: MyAppTheme.text,
                  )),
            ],
          ),
          Expanded(child: setListView())
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        PickupPol3Category pol3category = data[index];
        if (pol3category.Click == null) {
          pol3category.Click = false;
        }
        return Column(
          children: [
            Visibility(
                visible: Utils.isEmpty(pol3category.title) ? false : true,
                child: Text(
                  "-P",
                  style: MyAppTheme.text,
                )),
            Row(
              children: [
                Expanded(
                    flex: 1,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          Utils.isEmpty(pol3category.location) ? "--(${pol3category.locationQty})" : "${pol3category.location}(${pol3category.locationQty})",
                          style: MyAppTheme.test12,
                        ),
                        Visibility(
                            visible: Utils.isEmpty(pol3category.transferLocation) ? false : true,
                            child: Row(
                              children: [
                                Text(
                                  "transfer from:",
                                  style: MyAppTheme.test12,
                                ),
                                Text(
                                  Utils.getStringisEmpty(pol3category.transferLocation),
                                  style: MyAppTheme.testred12,
                                ),
                              ],
                            ))
                      ],
                    )),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      showDialog(
                        context: context,
                        builder: (context) => CustomDialog(),
                      );
                    });
                  },
                  child: Icon(
                    Icons.running_with_errors,
                    size: 18,
                    color: MyAppTheme.nearlyBlue,
                  ),
                ),
                SizedBox(
                  width: 3,
                ),
                Expanded(
                    flex: 1,
                    child: Text(
                      Utils.isEmpty(pol3category.sku) ? "--(${pol3category.pendingTotalQty}/${pol3category.pickedQty})" : "${pol3category.sku}(${pol3category.pendingTotalQty}/${pol3category.pickedQty})",
                      style: MyAppTheme.test12,
                    )),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      pol3category.Click = !pol3category.Click;
                    });
                  },
                  child: Icon(
                    pol3category.Click ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                    size: 20,
                    color: MyAppTheme.nearlyBlue,
                  ),
                ),
              ],
            ),
            Visibility(
                visible: pol3category.Click,
                child: Container(
                  margin: EdgeInsets.only(left: 5),
                  child: setListItemLpnView(pol3category.lpns),
                )),
            Visibility(
              visible: pol3category.Click && (pol3category.locations != null) && (pol3category.locations.length > 0) ? true : false,
              child: Container(
                margin: EdgeInsets.only(left: 5),
                child: Divider(),
              ),
            ),
            Visibility(visible: pol3category.Click, child: setListItemLocationView(pol3category.locations)),
            Divider(),
          ],
        );
      },
    );
  }

  ListView setListItemLpnView(List<Lpn> data) {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        Lpn pol3category = data[index];
        return Row(
          children: [
            SizedBox(
              width: 5,
            ),
            Expanded(
                flex: 1,
                child: Text(
                  Utils.getStringisEmpty(pol3category.trackingCode),
                  style: MyAppTheme.text_11_333333,
                )),
            Expanded(
                flex: 1,
                child: Text(
                  Utils.isEmpty(pol3category.lpn) ? "--(${pol3category.inventory})" : "${pol3category.lpn}(${pol3category.inventory})",
                  style: MyAppTheme.text_11_333333,
                )),
          ],
        );
      },
    );
  }

  ListView setListItemLocationView(List<PickLocationDetails> data) {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        PickLocationDetails pol3category = data[index];
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              Utils.getStringisEmpty(pol3category.location),
              style: MyAppTheme.text_11_333333,
            ),
            setListItemLpnView(pol3category.lpns)
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty( textEditingController.text)) {
      Toast.show("scan inbound lpn barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    getPickupLpnAndLocation( textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  void getTallyContainerNo() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    PickupPol3CategoryQr pickupPol3CategoryQr = new PickupPol3CategoryQr();
    pickupPol3CategoryQr.pickId = b2cPickBean.id == null ? null : '${b2cPickBean.id}';
    List<int> pickChildIds = new List();
    for (ChildPick childPick in b2cPickBean.childPicks) {
      pickChildIds.add(childPick.id);
    }
    pickupPol3CategoryQr.pickChildIds = pickChildIds;
    var json = jsonEncode(pickupPol3CategoryQr);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.pick_b2c_v2_queryPickItems, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => PickupPol3Category.fromJson(userJson)).toList());
      });
    } else if (baseResponse.status == 1701) {
      setState(() {
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => PickupPol3Category.fromJson(userJson)).toList());
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void getPickupLpnAndLocation(String text) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context, title: "Check...");
    } catch (e) {
      e.toString();
    }

    PickupPol3CategoryQr pickupPol3CategoryQr = new PickupPol3CategoryQr();
    pickupPol3CategoryQr.pickId = "${b2cPickBean.id}";
    pickupPol3CategoryQr.ibLpn = text;
    List<int> pickChildIds = pickupPol3CategoryQr.pickChildIds;

    for (ChildPick childPick in b2cPickBean.childPicks) {
      pickChildIds.add(childPick.id);
    }
    PickObLpn pickObLpn = new PickObLpn();
    pickObLpn.pickId = b2cPickBean.id;
    pickObLpn.obLpn = textEditingController.text;
    var json = jsonEncode(pickObLpn);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.pick_b2c_v2_checkIbLpn, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        b2cPickBean.iblpn = text;

        PickupPol3Location pickupPol3Location = PickupPol3Location.fromJson(baseResponse.data);
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => B2CPickSubmitScreen(b2cPickBean: b2cPickBean, pickupPol3OBLPN: pickupPol3Location)),
        ).then((value) => {getTallyContainerNo()});
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}

class CustomDialog extends StatefulWidget {
  @override
  _CustomDialogState createState() => _CustomDialogState();
}

class _CustomDialogState extends State<CustomDialog> {
  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("Other pick lists for this SKU need to be completed before handling its \"None Location\" sub-pick list.", style: MyAppTheme.textred14),
            SizedBox(height: 16.0),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Close',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
